<template>
	<div class="mc-popup-select-wrap">
		<div
			class="el-select"
			@click.stop="openDialog"
		>
			<div
				v-if="multiple"
				ref="tags"
				class="el-select__tags"
				:style="{
					'max-width': inputWidth - 32 + 'px',
					'width': '100%',
					'cursor': 'pointer',
				}"
			>
				<span v-if="collapseTags && tagsList.length">
					<Tag
						:closable="!selectDisabled"
						:size="collapseTagSize"
						type="info"
						disable-transitions
						@close="deleteTag($event, 0)"
					>
						<span class="el-select__tags-text">{{tagsList[0].fullName}}</span>
					</Tag>
					<Tag
						v-if="tagsList.length > 1"
						:closable="false"
						type="info"
						disable-transitions
					>
						<span class="el-select__tags-text">+ {{tagsList.length - 1}}</span>
					</Tag>
				</span>
				<transition-group
					v-if="!collapseTags"
					@after-leave="resetInputHeight"
				>
					<Tag
						v-for="(item, i) in tagsList"
						:key="item.id"
						:size="collapseTagSize"
						:closable="!selectDisabled"
						type="info"
						disable-transitions
						@close="deleteTag($event, i)"
					>
						<span class="el-select__tags-text">{{item.fullName}}</span>
					</Tag>
				</transition-group>
			</div>
			<Input
				ref="reference"
				v-model="innerValue"
				type="text"
				:placeholder="currentPlaceholder"
				:disabled="selectDisabled"
				readonly
				:validate-event="false"
				:tabindex="multiple ? '-1' : null"
				@mouseenter.native="inputHovering = true"
				@mouseleave.native="inputHovering = false"
			>
				<template #suffix>
					<i
						v-show="!showClose"
						:class="['el-select__caret', 'el-input__icon', 'el-icon-arrow-up']"
					/>
					<i
						v-if="showClose"
						class="el-select__caret el-input__icon el-icon-circle-close"
						@click="handleClearClick"
					/>
				</template>
			</Input>
		</div>
		<Dialog
			:visible.sync="visible"
			title="选择岗位"
			:close-on-click-modal="false"
			class="mc-dialog mc-dialog_center transfer-dialog"
			lock-scroll
			:append-to-body="true"
			width="800px"
			:modal-append-to-body="false"
			@close="onClose"
		>
			<div class="mc-transfer__body">
				<div class="transfer-pane">
					<div class="transfer-pane__tools">
						<Input
							v-model="keyword"
							placeholder="请输入关键词查询"
							clearable
							class="search-input"
							@keyup.enter.native="search"
						>
							<template #append>
								<Button

									icon="el-icon-search"
									@click="search"
								/>
							</template>
						</Input>
					</div>
					<div class="transfer-pane__body">
						<Tree
							ref="tree"
							v-loading="loading"
							:data="treeData"
							:props="props"
							check-on-click-node
							:expand-on-click-node="false"
							default-expand-all
							class="common-el-tree"
							node-key="id"
							:filter-node-method="filterNode"
							@node-click="handleNodeClick"
						>
							<template #default="{ node, data }">
								<span
									class="custom-tree-node"
								>
									<i :class="data.icon"/>
									<span class="text">{{node.label}}</span>
								</span>
							</template>
						</Tree>
					</div>
				</div>
				<div class="transfer-pane">
					<div class="transfer-pane__tools">
						<span>已选</span>
						<Button
							type="text"
							class="removeAllBtn"
							@click="removeAll"
						>
							清空列表
						</Button>
					</div>
					<div class="right-pane shadow transfer-pane__body">
						<div
							v-for="(item, index) in selectedData"
							:key="index"
							class="selected-item"
						>
							<span>{{item.fullName}}</span>
							<i
								class="el-icon-delete"
								@click="removeData(index)"
							/>
						</div>
					</div>
				</div>
			</div>
			<template #footer>
				<span
					class="dialog-footer"
				>
					<Button @click="setDefault(), (visible = false)">{{t("取消")}}</Button>
					<Button
						type="primary"
						@click="confirm"
					>{{t("确定")}}</Button>
				</span>
			</template>
		</Dialog>
	</div>
</template>

<script>
import {addResizeListener, removeResizeListener} from 'element-ui/src/utils/resize-event';
import {Tag, Input, Dialog, Tree, Button} from 'element-ui';
import {t} from '../../utils/index.js';
export default {
	name:'McPosSelect',
	components:{
		Tag, Input, Dialog, Tree, Button,
	},
	inject:{
		elForm:{
			default:'',
		},
		elFormItem:{
			default:'',
		},
	},
	props:{
		value:{
			default:'',
			type:String,
		},
		placeholder:{
			type:String,
			default:'请选择',
		},
		disabled:{
			type:Boolean,
			default:false,
		},
		multiple:{
			type:Boolean,
			default:false,
		},
		collapseTags:{
			type:Boolean,
			default:false,
		},
		clearable:{
			type:Boolean,
			default:false,
		},
		selectType:{
			type:String,
			default:'all',
		},
		ableDepIds:{
			type:Array,
			default: () => [],
		},
		ablePosIds:{
			type:Array,
			default: () => [],
		},
		size:String,
	},
	data(){
		return {
			t,
			treeData:[],
			allList:[],
			keyword:'',
			innerValue:'',
			visible:false,
			loading:false,
			props:{
				children:'children',
				label:'fullName',
				isLeaf:'isLeaf',
			},
			selectedData:[],
			tagsList:[],
			inputHovering:false,
			inputWidth:0,
			initialInputHeight:0,
		};
	},
	computed:{
		showClose(){
			const hasValue = this.multiple
				? Array.isArray(this.value) && this.value.length > 0
				: this.value !== undefined && this.value !== null && this.value !== '';
			const criteria
                = this.clearable && !this.selectDisabled && this.inputHovering && hasValue;
			return criteria;
		},
		currentPlaceholder(){
			if(this.multiple && Array.isArray(this.value) && this.value.length){
				return '';
			}else{
				return this.placeholder;
			}
		},
		selectDisabled(){
			return this.disabled || (this.elForm || {}).disabled;
		},
		_elFormItemSize(){
			return (this.elFormItem || {}).elFormItemSize;
		},
		selectSize(){
			return this.size || this._elFormItemSize || (this.$ELEMENT || {}).size;
		},
		collapseTagSize(){
			return ['small', 'mini'].indexOf(this.selectSize) > -1 ? 'mini' : 'small';
		},
	},
	watch:{
		visible(val){
			val && this.setDefault();
		},
		selectDisabled(){
			this.$nextTick(() => {
				this.resetInputHeight();
			});
		},
		allList:{
			handler:function(val){
				this.setDefault();
			},
			deep:true,
		},
	},
	created(){
		this.getData();
	},
	mounted(){
		addResizeListener(this.$el, this.handleResize);

		const reference = this.$refs.reference;
		if(reference && reference.$el){
			const sizeMap = {
				medium:36,
				small:32,
				mini:28,
			};
			const input = reference.$el.querySelector('input');
			this.initialInputHeight
                = input.getBoundingClientRect().height || sizeMap[this.selectSize];
		}
		if(this.multiple){
			this.resetInputHeight();
		}
		this.$nextTick(() => {
			if(reference && reference.$el){
				this.inputWidth = reference.$el.getBoundingClientRect().width;
			}
		});
		this.setDefault();
	},
	beforeUnmount(){
		if(this.$el && this.handleResize) removeResizeListener(this.$el, this.handleResize);
	},
	methods:{
		async getData(){
			//TODO 接口未迁移
			//this.allList = await this.$store.dispatch('base/getPositionList');
			//if(this.selectType === 'all'){
			//	this.treeData = await this.$store.dispatch('base/getPositionTree');
			//}
			//if(this.selectType === 'custom'){
			//	this.getAbleList();
			//}
		},
		getAbleList(){
			const data = {
				keyword:'',
				departIds:this.ableDepIds,
				positionIds:this.ablePosIds,
			};
			//this.$httpService({
			//	url:`/api/permission/Position/PositionCondition`,
			//	method:'post',
			//	data,
			//}).then((res) => {
			//	this.treeData = res.data.list;
			//});
		},
		onClose(){},
		openDialog(){
			if(this.selectDisabled) return;
			this.keyword = '';
			this.search();
			this.visible = true;
			if(this.selectType === 'all'){
				this.setDefault();
			}
			if(this.selectType === 'custom'){
				this.getData();
				this.$nextTick(() => {
					this.setDefault();
				});
			}
		},
		search(){
			this.$refs.tree && this.$refs.tree.filter(this.keyword);
		},
		filterNode(value, data){
			if(!value) return true;
			return data[this.props.label].indexOf(value) !== -1;
		},
		handleNodeClick(data){
			if(data.type !== 'Position') return;
			const boo = this.selectedData.some((o) => o.id === data.id);
			if(boo) return;
			this.multiple ? this.selectedData.push(data) : (this.selectedData = [data]);
		},
		removeAll(){
			this.selectedData = [];
		},
		removeData(index){
			this.selectedData.splice(index, 1);
		},
		confirm(){
			if(this.multiple){
				this.innerValue = '';
				this.tagsList = JSON.parse(JSON.stringify(this.selectedData));
				const selectedIds = this.selectedData.map((o) => o.id);
				this.$emit('input', selectedIds);
				this.$emit('change', selectedIds, this.selectedData);
			}else{
				if(!this.selectedData.length){
					this.innerValue = '';
					this.$emit('input', '');
					this.$emit('change', '', {});
					this.visible = false;
					return;
				}
				this.innerValue = this.selectedData[0].fullName;
				const selectedIds = this.selectedData[0].id;
				this.$emit('input', [selectedIds]);
				this.$emit('change', [selectedIds], this.selectedData[0]);
			}
			this.visible = false;
		},
		setDefault(){
			if(!this.value || !this.value.length){
				this.innerValue = '';
				this.selectedData = [];
				this.tagsList = [];
				return;
			}
			const selectedData = [];
			for(let i = 0; i < this.value.length; i++){
				const item = this.value[i];
				inner: for(let j = 0; j < this.allList.length; j++){
					if(item === this.allList[j].id){
						selectedData.push(this.allList[j]);
						break inner;
					}
				}
			}
			this.selectedData = selectedData;
			if(this.multiple){
				this.innerValue = '';
				this.tagsList = JSON.parse(JSON.stringify(this.selectedData));
				this.$nextTick(() => {
					this.resetInputHeight();
				});
			}else{
				if(!this.selectedData.length) return (this.innerValue = '');
				this.innerValue = this.selectedData[0].fullName;
			}
		},
		deleteTag(event, index){
			this.selectedData.splice(index, 1);
			this.confirm();
			event.stopPropagation();
		},
		handleClearClick(event){
			this.selectedData = [];
			this.confirm();
			event.stopPropagation();
		},
		resetInputWidth(){
			this.$nextTick(() => {
				if(this.$refs.reference && this.$refs.reference.$el){
					this.inputWidth = this.$refs.reference.$el.getBoundingClientRect().width;
				}else{
					console.warn('reference节点未找到');
				}
			});
		},
		handleResize(){
			this.resetInputWidth();
			if(this.multiple)this.resetInputHeight();
		},
		resetInputHeight(){
			if(this.collapseTags) return;
			this.$nextTick(() => {
				if(!this.$refs.reference) return;
				const inputChildNodes = this.$refs.reference.$el.childNodes;
				const input = [].filter.call(inputChildNodes, (item) => item.tagName === 'INPUT')[0];
				const tags = this.$refs.tags;
				const tagsHeight = tags ? Math.round(tags.getBoundingClientRect().height) : 0;
				const sizeInMap = this.initialInputHeight || 40;
				input.style.height
                    = this.selectedData.length === 0
						? sizeInMap + 'px'
						: Math.max(
							tags ? tagsHeight + (tagsHeight > sizeInMap ? 6 : 0) : 0,
							sizeInMap,
						) + 'px';
			});
		},
	},
};
</script>
<style lang="scss" scoped></style>